package my.consumer.demo.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import my.consumer.demo.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

@Service
public class RestTemplateService {
    @Autowired
    private RestTemplate restTemplate;

    /**
     * @HystrixCommand 表明该方法可熔断
     * fallbackMethod  指定一个熔断方法
     */
    @HystrixCommand(fallbackMethod = "getUserFallback")
    public User getUser(@RequestParam String userId) {
        User user = restTemplate.getForObject("http://userProvider/user/getUser?userId=" + userId, User.class);
        return user;
    }

    @HystrixCommand(fallbackMethod = "addUserFallback")
    public String addUser(@RequestBody User user) {
        String msg = restTemplate.postForEntity("http://userProvider/user/addUser", user, String.class).getBody();
        return msg;
    }

    /**
     * 熔断方法的  参数个数  和  参数类型  一定要和原方法对应上
     * 返回的类型也要和原方法一样
     * 关闭其中一个提供者，多次调用getUser方法
     * 控制台会打印fallback
     */
    private User getUserFallback(String userId) {
        System.out.println("getUser fallback!");
        return null;
    }

    private String addUserFallback(User user) {
        System.out.println("addUser fallback!");
        return "添加用户失败";
    }

}
